package structure.queue;

/**
* @description: 使用数组实现队列
 * 问题：添加，取出数据之后，当前空间不能在利用，会造成空间浪费。
* @author: wangjun
* @create: 2022-04-12
*/
public class QueueByArray {
    /**
     * 队列最大容量
     */
    private int maxSize;
    private int front;
    private int rear;
    private int[] queue;

    public QueueByArray() {

    }

    public QueueByArray(int maxSize) {
        this.maxSize = maxSize;
        // 头指针，指向第一个数据的前一个位置
        this.front = -1;
        // 尾指针，默认值为-1
        this.rear = -1;
        this.queue = new int[maxSize];
    }

    /**
     * 判断队列是否满了
     *
     * @return
     */
    public boolean isFull() {
        return rear == maxSize - 1;
    }

    /**
     * 判断队列是否为空
     *
     * @return
     */
    public boolean isEmpty() {
        return front == rear;
    }

    /**
     * 给队列添加数据
     *
     * @param value
     */
    public void addQueue(int value) {
        if (isFull()) {
            throw new RuntimeException("队列已满");
        }
        queue[++rear] = value;
    }

    /**
     * 获取队列数据
     */
    public int getQueue() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空");
        }
        System.out.println("队列front:" + front + ",rear:" + rear);
        return queue[++front];
    }

    /**
     * 遍历queue
     */
    public void showQueue() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空");
        }
        for (int i = 0; i < queue.length; i++) {
            System.out.printf("arr[%d]=%d\n", i, queue[i]);
        }
    }

    /**
     * 返回队列头数据
     *
     * @return
     */
    public int headQueue() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空");
        }
        return queue[front + 1];
    }
}